<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Article;
use Illuminate\Http\Request;
use App\Models\RechargeRecord;
use App\Models\MoneyLog;
use App\User;
use Illuminate\Support\Facades\Auth;
use EasyWeChat\Payment\Application;
use Illuminate\Support\Facades\Input;
use Omnipay\Omnipay;
class NotifyController extends Controller
{
    
    public function notify_url(Application $payment)
    {
        $response = $payment->handlePaidNotify(function($message, $fail){
            // file_put_contents('1.txt', json_encode($message));
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = RechargeRecord::where('out_trade_no', $message['out_trade_no'])->first();
            
            if (!$order) { // 如果订单不存在
                $fail('Order not exist.'); // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
        
            // 如果订单存在
            // 检查订单是否已经更新过支付状态
            if ($order->status == 1) { // 假设订单字段“支付时间”不为空代表已经支付
                return true; // 已经支付成功了就不再更新了
            }
        
            // 用户是否支付成功
            if ($message['result_code'] === 'SUCCESS') {
                // 不是已经支付状态则修改为已经支付状态
                $order->status = '1';
            } else { // 用户支付失败
                $order->status = '0';
            }
            $order->save(); // 保存订单
            //增加金额
			$MoneyLog = new MoneyLog();
			$MoneyLog->user_id = $order->user_id;
			$MoneyLog->money = $order->money;
			$MoneyLog->item_id = 0;
			$MoneyLog->item_type = '';
			$MoneyLog->content = '通过充值增加:'.$order->money.'元';
            $MoneyLog->save();
			//更新用户余额
			User::where('id', $order->user_id)->increment('money', $order->money);
        
            return true; // 返回处理完成
        });
        
        
        $response->send(); // return $response;
    }
    
    public function alipay_notify_url(Request $request)
    {
        $gateway = Omnipay::create('Alipay_AopPage');
        $gateway->setSignType('RSA2'); //RSA/RSA2
        $gateway->setAppId('2018030702330598');
        $gateway->setPrivateKey('MIIEowIBAAKCAQEAx/YWKgJyyKs84biLID/YB7YhCuotaGDma1YxFb8+p0j8Tj2XmOH+5B2Emrkj+FFS9eU4hNPbAcgw6g6weBEJKGf+kO7nR7Wd6VZ04/ciVp8r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34y6p5tuPyXYBPqyJdjCDrbd6dgghyLe3lYQKBgQDMyF/A+gsWNwZcJek6pqDVtiyOiAZgb6fGmguzDza9/4Z4/MfjeDU5uA23w5z6AOCAnzq+uC8Kg5/2nkXjKcDNbYpuacWVwEUUM5P+J3VLCyLvhrT4bNnC6AbsJ0SyAi17ZtZOLA6Syv4C6+sBd5LLlQdhFaSkhqNJaXbl8GRrkwKBgDWKq+bK+sdC+WX/V2pNPWe23/pIB94Tuqr2zkNha3aW4guHo1QUUHrdPCOt3zj3OJU1EXtA7ZSIFcyFNBsDbORK57/93ayKyDewpkc4Z+oDAelt7+nyTGiKSKJF05wIizZ/z5ika0oTa04zmfhiqBrPpuZAMcnccsSTk6xNdWrM');
        $gateway->setAlipayPublicKey('MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwGY+Ys/I9hgQG9OMwLOCEcdo4crdaSdPVsQNttCrdIcQ+GCZQba/DEoj+45HOWHodhj3Lkukn5eVM5cXUbCBQBthtS8BgAJj6HkpNF2ATKAkW5EJbRNxW2rDm05pA9mshqjB54HRkNzveoD9QV5s4xL2YOu48RJBe5eMQAckpDOw6wmEc180XYEATaHXzt621RDE9+S0k2lApifPGiA+J/+A4ABitIf9RYjKQn+gltWLu4X+stKJm7go207I24V9qrN0S9AamwRn4nuQFwDZoG7+Coz727LzgPeOlHY/AvBUF90fiTb6SS4QbKUk10YZW21RGyV5E+X6CRr0TexW/wIDAQAB');
        $gateway->setReturnUrl('http://www.textile-cards.com/user/reCharge');
        $gateway->setNotifyUrl('http://www.textile-cards.com/alipay/notify_url');
		
		
		
		$requests = $gateway->completePurchase();
		
		
		$requests->setParams(array_merge($_POST, $_GET)); //Don't use $_REQUEST for may contain $_COOKIE

		/**
		 * @var AopCompletePurchaseResponse $response
		 */
		try {
			$response = $requests->send();
			
			if($response->isPaid()){
				$data = $request->all();
				$order = RechargeRecord::where('out_trade_no', $data['out_trade_no'])->first();
				if (!$order) { // 如果订单不存在
					die('fail'); // The notify response
				}
				if ($order->status == 1) { // 假设订单字段“支付时间”不为空代表已经支付
					die('success'); // 已经支付成功了就不再更新了
				}
				$MoneyLog = new MoneyLog();
				$MoneyLog->user_id = $order->user_id;
				$MoneyLog->money = $order->money;
				$MoneyLog->item_id = 0;
				$MoneyLog->item_type = '';
				$MoneyLog->content = '通过充值增加:'.$order->money.'元';
				$MoneyLog->save();
				//更新用户余额
				User::where('id', $order->user_id)->increment('money', $order->money);
				$order->status = 1;
				$order->save();
				/**
				 * Payment is successful
				 */
				die('success'); //The notify response should be 'success' only
			}else{
				/**
				 * Payment is not successful
				 */
				die('fail'); //The notify response
			}
		} catch (Exception $e) {
			/**
			 * Payment is not successful
			 */
			die('fail'); //The notify response
		}
		
		
    }
    
    
}


